package com.fintech.third.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.fintech.third.model.ThirdProperties;
import com.fintech.third.utils.payment.HttpFormParameter;
import com.fintech.third.utils.payment.HttpMethod;
import com.fintech.third.utils.payment.HttpSendModel;
import com.fintech.third.utils.payment.SimpleHttpClient;
import com.fintech.third.utils.payment.SimpleHttpResponse;
import com.marvels.common.utils.MarvelsLogUtil;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpUtil {
	private static final MediaType String = null;
	private static final String APPLICATION_JSON = "application/json";
	/**
	 * 使用HttpClient发送post请求
	 * 
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String httpPostTongDun(String url, String jsonStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
		StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));
		httpPost.setEntity(se);
		httpPost.setURI(new URI(url));
		StringBuilder result = new StringBuilder();

		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent(), Charset.forName("UTF-8")));
			String string = "";
			while ((string = reader.readLine()) != null) {
				result.append(string);
			}
			reader.close();
		}
		return result.toString();
	}
	
	
	public static String httpPost(String url) throws ConnectTimeoutException, SocketTimeoutException, Exception{
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
		httpPost.setURI(new URI(url));
		StringBuilder result = new StringBuilder();
		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent(), Charset.forName("UTF-8")));
			String string = "";
			while ((string = reader.readLine()) != null) {
				result.append(string);
			}
			reader.close();
		}
		return result.toString();
	}
	
	
	/**
	 * 使用HttpClient发送get请求
	 * 
	 * @param arg
	 * @return
	 * @throws IOException
	 */
	public static String httpGetTongDun(String url) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		StringBuilder result = new StringBuilder();
		httpGet.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
		HttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			String str;
			while ((str = reader.readLine()) != null) {
				result.append(str);
			}
			reader.close();
		}

		return result.toString();
	}
	/**
	 * 使用HttpClient发送post请求
	 * 
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String httpPost(String url, String jsonStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
		StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));
		se.setContentType("text/json");
		httpPost.setEntity(se);
		httpPost.setURI(new URI(url));
		StringBuilder result = new StringBuilder();
		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent(), Charset.forName("UTF-8")));
			String string = "";
			while ((string = reader.readLine()) != null) {
				result.append(string);
			}
			reader.close();
		}
		return result.toString();
	}

	
	
	
	/**
	 * 使用HttpClient发送post请求(忽略证书)
	 * 
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String httpPost2(String url, String jsonStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		enableSSL(httpClient);
		HttpPost httpPost = new HttpPost();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);

		StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));

		se.setContentType("text/json");
		httpPost.setEntity(se);

		httpPost.setURI(new URI(url));

		StringBuilder result = new StringBuilder();

		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent(), Charset.forName("UTF-8")));
			String string = "";
			while ((string = reader.readLine()) != null) {
				result.append(string);
			}
			reader.close();
		}
		return result.toString();
	}
	
	
	
	/**
	 * 使用HttpClient发送get请求
	 * 
	 * @param arg
	 * @return
	 * @throws IOException
	 */
	public static String httpGet(String url) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		StringBuilder result = new StringBuilder();
		httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		HttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			String str;
			while ((str = reader.readLine()) != null) {
				result.append(str);
			}
			reader.close();
		}

		return result.toString();
	}

	
	/**
	 * 使用HttpClient发送get请求
	 * 
	 * @param arg
	 * @return
	 * @throws IOException
	 */
	public static String httpGetTimeSet(String url) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true));
		StringBuilder result = new StringBuilder();
		httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		HttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
			String str;
			while ((str = reader.readLine()) != null) {
				result.append(str);
			}
			reader.close();
		}

		return result.toString();
	}
	/**
	 * 金阁签章
	 * 
	 * @param url
	 * @return
	 * @throws TimeoutException
	 * @throws Exception
	 */
	public static String httpGetJg(String url) throws ConnectTimeoutException, SocketTimeoutException, Exception{

		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		StringBuilder result = new StringBuilder();
		InputStream in = null;
		httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		HttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			in = entity.getContent();
		}
		String base64Str = Base64Util.getPDFBinary(in);
		return base64Str;
	}

	/**
	 * 使用HttpClient发送get请求
	 * 
	 * @param arg
	 * @return @throws
	 */
	public static String httpGetEn(String url) throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		StringBuilder result = new StringBuilder();
		httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		HttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
			String str;
			while ((str = reader.readLine()) != null) {
				result.append(str);
			}
		}

		return result.toString();
	}
	
	
	
	/**
	 * 宝付TLSv1.1，TLSv1.2 请求
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String baoFuHttpRequest(String url) throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
		StringBuilder result = new StringBuilder();
		httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		if (url.startsWith("https://")) {
			try {
				SSLContext ctx = SSLContext.getInstance("TLSv1.2");
				X509TrustManager tm = new X509TrustManager() {
					@Override
					public void checkClientTrusted(X509Certificate[] chain, String authType)
							throws CertificateException {
					}
					@Override
					public void checkServerTrusted(X509Certificate[] chain, String authType)
							throws CertificateException {
					}
					@Override
					public X509Certificate[] getAcceptedIssuers() {
						return null;
					}
				};
				ctx.init(null, new TrustManager[] { tm }, null);
				SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				ClientConnectionManager ccm = httpClient.getConnectionManager();
				SchemeRegistry sr = ccm.getSchemeRegistry();
				sr.register(new Scheme("https", 443, ssf));
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>>>>宝付TLSv1.1，TLSv1.2请求异常:",e);
			}
		}
		HttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
			String str;
			while ((str = reader.readLine()) != null) {
				result.append(str);
			}
		}

		return result.toString();
	}
	
	
	

	/**
	 * 使用OkHttpClient发送post请求
	 * 
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 */
	public static String okHttpPost(String url, String json) throws IOException {

		OkHttpClient client = new OkHttpClient();
		RequestBody body = RequestBody.create(String, json);
		Request request = new Request.Builder().url(url).post(body).build();
		Response response = client.newCall(request).execute();
		if (response.isSuccessful()) {
			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}

	/**
	 * 利用httpclient跳过证书访问https
	 * 
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String post(String url, String str) throws IOException, URISyntaxException {
		HttpClient httpClient = new DefaultHttpClient();
		enableSSL(httpClient);
		HttpPost httpPost = new HttpPost();
		httpPost.setEntity(new StringEntity(str, Charset.forName("UTF-8")));
		httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
		httpPost.setURI(new URI(url));

		StringBuilder result = new StringBuilder();

		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
			String string;
			while ((string = reader.readLine()) != null) {
				result.append(string);
			}
		}

		return result.toString();
	}


	/**
	 * 速盾短信发送 
	 * @param url
	 * @param map
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String postSpeedShield(String url, Map<String, String> map) throws IOException, URISyntaxException {
		org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		PostMethod post = new PostMethod(url);
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		post.setRequestBody( new org.apache.commons.httpclient.NameValuePair[] { 
		        new org.apache.commons.httpclient.NameValuePair("account",map.get("account")), 
		        new org.apache.commons.httpclient.NameValuePair("pswd", map.get("pswd")), 
		        new org.apache.commons.httpclient.NameValuePair("mobile", map.get("mobile")), 
		        new org.apache.commons.httpclient.NameValuePair("needstatus",map.get("needstatus")), 
		        new org.apache.commons.httpclient.NameValuePair("msg", URLEncoder.encode(map.get("msg"), "UTF-8")), 
		        new org.apache.commons.httpclient.NameValuePair("extno", map.get("extno")) });
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int responseCode = httpClient.executeMethod(post);
		if (responseCode == 200) {
			InputStream in = post.getResponseBodyAsStream();

			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
		}
		String result = URLDecoder.decode(baos.toString(), "UTF-8");
		return result;
	}

	
	/**
	 * 速盾短信发送 
	 * @param url
	 * @param map
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String postSpeedShield2(String url, Map<String, String> map) throws IOException, URISyntaxException {
		org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		PostMethod post = new PostMethod(url);
		org.apache.commons.httpclient.NameValuePair[] nameValuePair=new org.apache.commons.httpclient.NameValuePair[map.keySet().size()];
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		int i=0;
		for(String key:map.keySet()){
			nameValuePair[i]= new org.apache.commons.httpclient.NameValuePair(key,map.get(key));
					i++;
		}
		post.setRequestBody(nameValuePair);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int responseCode = httpClient.executeMethod(post);
		if (responseCode == 200) {
			InputStream in = post.getResponseBodyAsStream();

			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
		}
		String result = URLDecoder.decode(baos.toString(), "UTF-8");
		return result;
	}
	
	
	 public static String getHttpResp( String httpUrl,Map<String, String> reqMap) throws IOException, URISyntaxException{
		String result = "";
		org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		PostMethod post = new PostMethod(httpUrl);
		org.apache.commons.httpclient.NameValuePair[] nameValuePair = new org.apache.commons.httpclient.NameValuePair[reqMap
				.keySet().size()];
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		int i = 0;
		for (String key : reqMap.keySet()) {
			nameValuePair[i] = new org.apache.commons.httpclient.NameValuePair(key, reqMap.get(key));
			i++;
		}
		post.setRequestBody(nameValuePair);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int responseCode = httpClient.executeMethod(post);
		if (responseCode == 200) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "UTF-8"));
			String curline = "";
			while ((curline = reader.readLine()) != null) {
				result += curline;
			}
		}

		return result;
	}
	 
	 
	/**
	 * 富数利用httpclient跳过证书访问https
	 * 
	 * @param map
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static String richNumberPost(Map<String, String> map, String url) throws IOException, URISyntaxException {
		HttpClient httpClient = new DefaultHttpClient();
		enableSSL(httpClient);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		List<NameValuePair> nvps2 = new ArrayList<NameValuePair>();
		for (String key : map.keySet()) {
			nvps2.add(new BasicNameValuePair(key, map.get(key)));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(nvps2, "UTF-8"));
		StringBuilder result = new StringBuilder();
		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
			String string;
			while ((string = reader.readLine()) != null) {
				result.append(string);
			}
		}

		return result.toString();
	}

	/**
	 * 重写验证方法，取消检测ssl
	 */
	private static TrustManager truseAllManager = new X509TrustManager() {

		public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}

	};

	// 调用ssl
	private static void enableSSL(HttpClient httpClient) {

		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpClient.getConnectionManager().getSchemeRegistry().register(https);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 调用ssl
	private static void enableSSLOther(HttpClient httpClient) {

		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpClient.getConnectionManager().getSchemeRegistry().register(https);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 依图post请求
	 * 
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String httpPostYT(String url, String jsonStr) throws Exception {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost();
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		PublicKey publicKey = EncryptionHelper.RSAHelper
				.loadPublicKey(ThirdSystemUtil.class.getResource(thirdProperties.getYt_public_key()).getPath());
		httpPost.addHeader("x-access-id", thirdProperties.getYt_access_id());
		httpPost.addHeader("x-signature",
				HttpRequestHelper.generateSignature(publicKey, thirdProperties.getYt_signature_key(), jsonStr, "fjjf"));
		StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));

		se.setContentType("text/json");
		httpPost.setEntity(se);

		httpPost.setURI(new URI(url));

		String result = "";

		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent(), Charset.forName("UTF-8")));
			result = reader.readLine();
		}

		return result;
	}
	
	
	public static String httpPost(String url, String jsonStr,Header[] headers) throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost();
		httpPost.addHeader("Content-Type", "application/json");
		httpPost.addHeader("Accept", "application/json");
		if(headers!=null && headers.length>0){
			for(Header header:headers){
				httpPost.addHeader(header);
			}
		}
		StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));
		se.setContentType("text/json");
		httpPost.setEntity(se);
		httpPost.setURI(new URI(url));
		String result = "";
		HttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(entity.getContent(), Charset.forName("UTF-8")));
			result = reader.readLine();
		}

		return result;
	}
	
	
	
	public static String RequestForm(String Url,Map<String,String> Parms) throws Exception{		
		if(Parms.isEmpty()){
			return  "参数不能为空！";
		}
		String PostParms = "";
		int PostItemTotal = Parms.keySet().size();
		int Itemp=0;
		for (String key : Parms.keySet()){
			PostParms += key + "="+Parms.get(key);
			Itemp++;
			if(Itemp<PostItemTotal){
				PostParms +="&";
			}
		}
		MarvelsLogUtil.getInstance().info(PostParms);
		HttpSendModel httpSendModel = new HttpSendModel(Url + "?" + PostParms);
		httpSendModel.setMethod(HttpMethod.POST);
		SimpleHttpResponse response = null;
		response = doRequest(httpSendModel, "utf-8");
		return response.getEntityString();

	}
	
	public static SimpleHttpResponse doRequest(HttpSendModel httpSendModel,
			String getCharSet) throws Exception {

		// 创建默认的httpClient客户端端
		SimpleHttpClient simpleHttpclient = new SimpleHttpClient();

		try {
			return doRequest(simpleHttpclient, httpSendModel, getCharSet);
		} finally {
			simpleHttpclient.getHttpclient().getConnectionManager().shutdown();
		}

	}
	
	
	/**
	 * @param httpclient
	 * @param httpSendModel
	 * @param getCharSet
	 * @return
	 * @throws Exception 
	 */
	public static SimpleHttpResponse doRequest(
			SimpleHttpClient simpleHttpclient, HttpSendModel httpSendModel,
			String getCharSet) throws Exception {

		HttpRequestBase httpRequest = buildHttpRequest(httpSendModel);

		if (httpSendModel.getUrl().startsWith("https://")) {
			simpleHttpclient.enableSSL();
		}

		try {
			HttpResponse response = simpleHttpclient.getHttpclient().execute(
					httpRequest);
			int statusCode = response.getStatusLine().getStatusCode();

			if (SimpleHttpResponse.isRequestSuccess(statusCode)) {
				return new SimpleHttpResponse(statusCode, EntityUtils.toString(
						response.getEntity(), getCharSet), null);
			} else {
				return new SimpleHttpResponse(statusCode, null, response
						.getStatusLine().getReasonPhrase());
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("http请求异常", e);
		}

	}
	
	/**
	 * @param httpSendModel
	 * @return
	 * @throws Exception 
	 */
	protected static HttpRequestBase buildHttpRequest(
			HttpSendModel httpSendModel) throws Exception {
		HttpRequestBase httpRequest;
		if (httpSendModel.getMethod() == null) {
			throw new Exception("请求方式未设定");
		} else if (httpSendModel.getMethod() == HttpMethod.POST) {

			String url = httpSendModel.getUrl();
			String sendCharSet = httpSendModel.getCharSet();
			List<HttpFormParameter> params = httpSendModel.getParams();
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
			if (params != null && params.size() != 0) {

				for (HttpFormParameter param : params) {
					qparams.add(new BasicNameValuePair(param.getName(), param
							.getValue()));
				}

			}

			HttpPost httppost = new HttpPost(url);
			try {
				httppost.setEntity(new UrlEncodedFormEntity(qparams,
						sendCharSet));
			} catch (UnsupportedEncodingException e) {
				throw new Exception("构建post请求参数失败", e);
			}

			httpRequest = httppost;
		} else if (httpSendModel.getMethod() == HttpMethod.GET) {
			HttpGet httpget = new HttpGet(httpSendModel.buildGetRequestUrl());

			httpRequest = httpget;
		} else {
			throw new Exception("请求方式不支持：" + httpSendModel.getMethod());
		}

		return httpRequest;
	}
	/**
	 * 
	* @Title: SMS 
	* @Description: 互盟推送短信调用 
	* @param postData
	* @param postUrl
	* @return       
	* @author 李瑶
	* @date 2018年3月26日 下午4:39:32
	 */
	public static String SMS(String postData, String postUrl) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();

            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
            MarvelsLogUtil.getInstance().error(">>>>>>>>>>互盟短信发送异常:"+e);
        }
        return "";
    }
}